-module(app_rewrite).
-include("yaws_api.hrl").
-export([arg_rewrite/1]).

arg_rewrite(Arg) ->
	BizCookie = "bizcookie",
	H = Arg#arg.headers,
	case get_cookie_val(BizCookie, H) of
	{ok, Session} ->
		io:format("get cookie:~p~n",[Session]),
		gen_server:call(list_to_pid(Session),ping),
		Arg#arg{opaque=list_to_pid(Session)};
	_ ->
		{ok,Pid} = web_sup:start_child(),
		Cookie = yaws_api:new_cookie_session(pid_to_list(Pid)),
		Req = Arg#arg.req,
		{abs_path, Path} = Req#http_request.path,
		Arg#arg{opaque=Pid,
					req = 
						Req#http_request{path = {abs_path,"/scripts/rebounce.yaws?"}},
					state = {abs_path, Path}
		}		
	end.
	
get_cookie_val(C,H) ->
	case yaws_api:find_cookie_val(C,H#headers.cookie) of
	[] ->
		%% login required
		{error,login_require};
	Cookie ->
		yaws_api:cookieval_to_opaque(Cookie)
	end.
login_pages() ->
	["login_control.yaws"].
	
